package com.slkj.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.slkj.dto.CountiesTaskDTO;
import com.slkj.dto.SpecialTaskDTO;
import com.slkj.dto.UserinfoDTO;
import com.slkj.entity.*;
import com.slkj.mapper.*;
import org.activiti.engine.*;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author admin
 * @version 1.0.0
 * @ClassName CountiesService.java
 * @Description TODO
 * @createTime 2020年03月20日 13:54:00
 */
@Service
public class CountiesService {

    @Autowired
    CountiesTaskMapper countiesTaskMapper;

    @Autowired
    CountiesNodeMapper countiesNodeMapper;

    @Autowired
    CountiesDutyMapper countiesDutyMapper;

    @Autowired
    CheckUnitMapper checkUnitMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    UserService userService;

    @Autowired
    FileMapper fileMapper;


    @Autowired
    RepositoryService repositoryService;

    @Autowired
    RuntimeService runtimeService;

    @Autowired
    HistoryService historyService;

    @Autowired
    TaskService taskService;


    private Logger log = LoggerFactory.getLogger(CountiesService.class);

    public void createTask(CountiesTask countiesTask, String username) {
        List<String> checkUnitList = countiesTask.getCheckUnitList();
        List<String> toCheckUnitList = countiesTask.getToCheckUnitList();
        List<CountiesNode> countiesNodeList = countiesTask.getCountiesNodeList();
        if (checkUnitList == null || toCheckUnitList == null || countiesNodeList == null) {
            log.error("checkUnitList/toCheckUnitList/countiesNodeList------------>>" + "空指针异常");
            throw new NullPointerException("空指针异常");
        }

        if (checkUnitList.size() == 0 || checkUnitList.size() == 0 || countiesNodeList.size() == 0) {
            log.error("checkUnitList/toCheckUnitList/countiesNodeList------------>>" + "空指针异常");

            throw new NullPointerException("空指针异常");
        }

        Userinfo userinfo = userMapper.selectByUsername(username);
        UserinfoDTO userinfoDTO = userService.getUserinfo(userinfo.getId());
        String type = userinfoDTO.getType();
        if (StringUtils.isBlank(type)) {
            log.error("任务发起人type为空------------>>");
            throw new RuntimeException("任务发起人type为空");
        }
        countiesTask.setUsername(userinfoDTO.getUsername());
        countiesTask.setUserType(type);
        List<Userinfo> checkUnitUserList = userMapper.selectByUserIdList(checkUnitList);
        List<Userinfo> toCheckUnitUserList = userMapper.selectByUserIdList(toCheckUnitList);

        if (checkUnitUserList == null || toCheckUnitUserList == null) {
            log.error("checkUnitUserList/toCheckUnitUserList------------>>" + "空指针异常");
            throw new NullPointerException("空指针异常");
        }

        if (checkUnitUserList.size() == 0 || toCheckUnitUserList.size() == 0) {
            log.error("checkUnitUserList/toCheckUnitUserList------------>>" + "空指针异常");
            throw new NullPointerException("空指针异常");
        }

        countiesTaskMapper.insert(countiesTask);
        checkUnitMapper.insert(checkUnitUserList, countiesTask.getId());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
        String taskId = countiesTask.getId();
        for (CountiesNode countiesNode : countiesNodeList) {
            countiesNode.setCountiesTaskId(taskId);
            List<String> projectTime = countiesNode.getProjectTime();
            if (projectTime == null || projectTime.size() == 0) {
                throw new NullPointerException("空指针异常");
            }
            try {
                countiesNode.setCountiesBeginTime(simpleDateFormat.parse(projectTime.get(0)));
                countiesNode.setCountiesEndTime(simpleDateFormat.parse(projectTime.get(1)));
            } catch (ParseException e) {
                log.error("日期格式转换异常");
                e.printStackTrace();
                throw new RuntimeException("日期格式转换异常");
            }
            countiesNodeMapper.insert(countiesNode);
            String countiesNodeId = countiesNode.getId();
            SimpleDateFormat simpleDateFormatYear = new SimpleDateFormat("yyyy");

            Date countiesEndTime = countiesNode.getCountiesEndTime();
            List<File> fileList = countiesNode.getFileList();
            for (Userinfo toCheckUnitUser : toCheckUnitUserList) {
                CountiesDuty countiesDuty = new CountiesDuty();
                countiesDuty.setUserId(toCheckUnitUser.getId());
                countiesDuty.setUsername(toCheckUnitUser.getUsername());
                countiesDuty.setName(toCheckUnitUser.getName());
                countiesDuty.setCountiesLight("灰灯");
                countiesDuty.setCountiesAuditStatus("待上传");
                countiesDuty.setCountiesCheckAudit("待上传");
                countiesDuty.setCountiesPerAudit("待上传");
                countiesDuty.setCountiesNodeId(countiesNodeId);
                countiesDuty.setCountiesProjectTime(countiesEndTime);
                countiesDuty.setCountiesTaskId(taskId);
                countiesDuty.setCountiesYear(simpleDateFormatYear.format(new Date()));
                countiesDutyMapper.insert(countiesDuty);

                if (fileList != null && fileList.size() != 0) {
                    fileMapper.insert(fileList, countiesDuty.getId(), "3");
                }
                Map map = new HashMap();
                map.put("countiesName", countiesDuty.getUsername());
                ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("Counties", CountiesDuty.class.getSimpleName().toLowerCase() + "/" + countiesDuty.getId(), map);
                Task task = taskService.createTaskQuery().processInstanceId(processInstance.getProcessInstanceId()).taskAssignee(countiesDuty.getUsername()).singleResult();
                taskService.complete(task.getId());
            }
        }

//        userMapper.getUserinfoByUserId()
    }

    public PageInfo<SpecialTaskDTO> getTaskFeedback(String title, Date beginDate, Date endDate, String light, String username, int gotoPage, int pageSize, String checkUnitUserId, String toCheckUnitUserId, String status) {

        PageHelper.startPage(gotoPage, pageSize, true);
        List<CountiesTaskDTO> countiesTaskDTOList = countiesDutyMapper.selectCountiesTaskDTO(title, beginDate, endDate, light, username, checkUnitUserId, toCheckUnitUserId,status);
        PageInfo pageInfo = new PageInfo(countiesTaskDTOList);
        if (countiesTaskDTOList != null && countiesTaskDTOList.size() != 0) {
            List<CheckUnit> checkUnitList = checkUnitMapper.selectByCountiesTaskDTOList(countiesTaskDTOList);
            List<File> fileList = fileMapper.selectByCountiesTaskDTOList(countiesTaskDTOList, "4");
            if (checkUnitList == null || checkUnitList.size() == 0) {
                throw new RuntimeException("查询时出现异常");
            }

            for (CountiesTaskDTO countiesTaskDTO : countiesTaskDTOList) {
                String checkUnitString = "";
                for (CheckUnit checkUnit : checkUnitList) {
                    if (countiesTaskDTO.getTaskId().equals(checkUnit.getCountiesTaskId())) {
                        checkUnitString = checkUnitString + ";" + checkUnit.getName();
                    }
                }
                if (checkUnitString.charAt(0) == ';') {
                    checkUnitString = checkUnitString.substring(1);
                }
                countiesTaskDTO.setCheckUnit(checkUnitString);
            }
            if (fileList != null && fileList.size() != 0) {
                for (CountiesTaskDTO countiesTaskDTO : countiesTaskDTOList) {
                    boolean result = false;
                    List<File> countiesFileList = new ArrayList<>();
                    for (File file : fileList) {
                        if (countiesTaskDTO.getId().equals(file.getDutyId())) {
                            result = true;
                            countiesFileList.add(file);
                        }
                    }
                    if (result) {
                        countiesTaskDTO.setFileList(countiesFileList);
                    }
                }
            }
        }
        return pageInfo;
    }


    private void taskComplete(List<Map> mapList, int count, String dutyId) throws SQLException {
        CountiesDuty countiesDuty = countiesDutyMapper.selectByDutyId(dutyId);
        if (countiesDuty == null) {
            throw new SQLException("查询时出现异常");
        }
        String buniessKey = countiesDuty.getClass().getSimpleName().toLowerCase() + "/" + countiesDuty.getId();
        String buniessKeyCheck = countiesDuty.getClass().getSimpleName().toLowerCase() + "check/" + countiesDuty.getId();
        String buniessKeyLight = countiesDuty.getClass().getSimpleName().toLowerCase() + "light/" + countiesDuty.getId();
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(buniessKey).singleResult();
        ProcessInstance processInstanceCheck = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(buniessKeyCheck).singleResult();
        ProcessInstance processInstanceLight = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(buniessKeyLight).singleResult();
        ProcessInstance processInstanceTask = null;
        if (processInstance != null) {
            processInstanceTask = processInstance;
        } else if (processInstanceCheck != null) {
            processInstanceTask = processInstanceCheck;
        } else if (processInstanceLight != null) {
            processInstanceTask = processInstanceLight;
        } else {
            throw new ActivitiException("找不到流程任务实例");
        }
        for (int i = 0; i < count; i++) {
            Task task = taskService.createTaskQuery().processInstanceId(processInstanceTask.getProcessInstanceId()).taskAssignee(countiesDuty.getUsername()).singleResult();
            if (mapList != null && mapList.size() != 0) {
                if (mapList.get(count - 1) != null) {
                    taskService.complete(task.getId(), mapList.get(count - 1));
                } else {
                    taskService.complete(task.getId());
                }
            } else {
                taskService.complete(task.getId());
            }
        }

    }

    public void taskUpload(List<File> fileList, String dutyId, List<Map> variables, String count) throws SQLException {
        CountiesDuty countiesDuty = countiesDutyMapper.selectByDutyId(dutyId);
        if (countiesDuty == null) {
            throw new SQLException("找不到该任务");
        }
        fileMapper.insert(fileList, dutyId, "3");
        taskComplete(variables, Integer.parseInt(count), dutyId);
        countiesDutyMapper.updateStatusById("黄灯", "待审核", "待审核", "待审核", dutyId);
        countiesDutyMapper.updateSubmitTime(new Date(), dutyId);
    }

    public void audit(List<Map> variables, String count, List<String> dutyIdList, String score, String completeCase, String auditIdea) throws SQLException {
        for (String dutyId : dutyIdList) {
            CountiesDuty countiesDuty = countiesDutyMapper.selectByDutyId(dutyId);
            if (countiesDuty == null) {
                throw new SQLException("找不到该任务");
            }
            Map map = variables.get(0);
            String isPass = String.valueOf(map.get("isPass"));
            String perStatus = "";
            String light = "";
            String status = "";
            if (StringUtils.isNotBlank(isPass)) {
                if (isPass.equals("通过")) {
                    light = "黄灯";
                    perStatus = "待审核";
                    status = "待审核";
                } else if (isPass.equals("未完成")) {
                    light = "红灯";
                    perStatus = "待审核";
                    status = "未完成";
                } else if (isPass.equals("驳回")) {
                    light = "蓝灯";
                    perStatus = "待审核";
                    status = "驳回";
                } else {
                    throw new RuntimeException("参数异常");
                }
            } else {
                throw new RuntimeException("参数异常");
            }
            if (countiesDuty.getCountiesCheckAudit().equals("通过") || countiesDuty.getCountiesCheckAudit().equals("未完成") || countiesDuty.getCountiesCheckAudit().equals("驳回")) {
                String buniessKey = countiesDuty.getClass().getSimpleName().toLowerCase() + "/" + countiesDuty.getId();
                String buniessKeyCheck = countiesDuty.getClass().getSimpleName().toLowerCase() + "check/" + countiesDuty.getId();
                ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(buniessKey).singleResult();
                ProcessInstance processInstanceCheck = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(buniessKeyCheck).singleResult();
                if (processInstance != null) {
                    runtimeService.deleteProcessInstance(processInstance.getProcessInstanceId(), "processInstance delete");
                }
                if (processInstanceCheck != null) {
                    runtimeService.deleteProcessInstance(processInstanceCheck.getProcessInstanceId(), "processInstance delete");
                }
                variables.get(0).put("countiesName", countiesDuty.getUsername());
                runtimeService.startProcessInstanceByKey("CountiesCheck", CountiesDuty.class.getSimpleName().toLowerCase() + "check/" + countiesDuty.getId(), variables.get(0));
            } else {
                taskComplete(variables, Integer.parseInt(count), dutyId);
            }
            countiesDutyMapper.updateStatusById(light, status, isPass, perStatus, dutyId);
            countiesDutyMapper.updateCheck(score, completeCase, auditIdea, dutyId);
        }

    }

    public void passTask(List<String> dutyIdList, List<Map> variables, String count) throws SQLException {
        for (String dutyId : dutyIdList) {
            CountiesDuty countiesDuty = countiesDutyMapper.selectByDutyId(dutyId);
            if (countiesDuty == null) {
                throw new SQLException("找不到该任务");
            }
            if (!countiesDuty.getCountiesCheckAudit().equals("通过") && !countiesDuty.getCountiesCheckAudit().equals("未完成")) {
                throw new RuntimeException("不能越级审核");
            }
            taskComplete(variables, Integer.parseInt(count), dutyId);
            countiesDutyMapper.updateStatusById("绿灯", "已完成", countiesDuty.getCountiesCheckAudit(), variables.get(0).get("isPass") + "", dutyId);
        }
    }

    public void noPassTask(List<String> dutyIdList, List<Map> variables, String count) throws SQLException {
        for (String dutyId : dutyIdList) {
            CountiesDuty countiesDuty = countiesDutyMapper.selectByDutyId(dutyId);
            if (countiesDuty == null) {
                throw new SQLException("查询时出现异常");
            }
            if (!countiesDuty.getCountiesCheckAudit().equals("通过") && !countiesDuty.getCountiesCheckAudit().equals("未完成")) {
                throw new RuntimeException("不能越级审核");
            }
            taskComplete(variables, Integer.parseInt(count), dutyId);
            countiesDutyMapper.updateStatusById("蓝灯", "驳回", countiesDuty.getCountiesCheckAudit(), variables.get(0).get("isPass") + "", dutyId);
        }
    }


    public void lightAdjust(List<String> dutyIdList, String light, List<Map> mapList, String lightCause) throws SQLException {
        for (String dutyId : dutyIdList) {
            CountiesDuty countiesDuty = countiesDutyMapper.selectByDutyId(dutyId);
            if (countiesDuty == null) {
                throw new SQLException("找不到该任务");
            }
            String buniessKey = countiesDuty.getClass().getSimpleName().toLowerCase() + "/" + countiesDuty.getId();
            String buniessKeyCheck = countiesDuty.getClass().getSimpleName().toLowerCase() + "check/" + countiesDuty.getId();
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(buniessKey).singleResult();
            ProcessInstance processInstanceCheck = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(buniessKeyCheck).singleResult();
            if (processInstance != null) {
                runtimeService.deleteProcessInstance(processInstance.getProcessInstanceId(), "processInstance delete");
            }
            if (processInstanceCheck != null) {
                runtimeService.deleteProcessInstance(processInstanceCheck.getProcessInstanceId(), "processInstance delete");
            }
            mapList.get(0).put("countiesName", countiesDuty.getUsername());
            if (countiesDuty.getCountiesLight().equals(light)) {
                return;
            }
            runtimeService.startProcessInstanceByKey("Countieslight", CountiesDuty.class.getSimpleName() + "light/" + countiesDuty.getId(), mapList.get(0));
            countiesDutyMapper.updateStatusById(light, mapList.get(0).get("isPass") + "", countiesDuty.getCountiesCheckAudit(), mapList.get(0).get("isPass") + "", dutyId);
            countiesDutyMapper.updateLightCase(lightCause, dutyId);
        }
    }

}
